package net.xdlass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdlass.config.SmsConfig;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@Component
public class SmsComponent {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SmsConfig smsConfig;

    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    public void send(String toPhone, String templateId, String value){
        String url = String.format(URL_TEMPLATE, toPhone, templateId, value);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization","APPCODE "+smsConfig.getAppCode());
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(httpHeaders), String.class);
        log.info("url={},body={}", url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }
    }
}
